package com.lbj.dao.impl;

import com.lbj.dao.CommentDao;
import com.lbj.domain.Comment;
import com.lbj.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class CommentDaoImpl implements CommentDao {
    JDBCUtil jdbcUtil = new JDBCUtil();
    Connection conn = jdbcUtil.createCon();

    @Override
    public List<Comment> getComments(String topicId) {
        String sql =" select * from tbl_comment where topicId = ? order by createTime desc ";
        List<Comment> comments = new ArrayList<>();
        ResultSet rs = null;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1,topicId);
            rs = pst.executeQuery();
            while (rs.next()){
                String id = rs.getString(1);
                String content = rs.getString(2);
                String userId = rs.getString(4);
                String createTime = rs.getString(5);
                Comment comment = new Comment(id,content,topicId,userId,createTime);
                comments.add(comment);
            }
            rs.close();
            pst.close();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }

        return comments;
    }

    @Override
    public int addComment(Comment comment) {
        String sql = "insert into tbl_comment values(?,?,?,?,?)";
        int row = 1;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1,comment.getId());
            pst.setString(2,comment.getContent());
            pst.setString(3,comment.getTopicId());
            pst.setString(4,comment.getUserId());
            pst.setString(5,comment.getCreateTime());
            row = pst.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}
